package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.rdb.api.GeolocationRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.AdGeolocation;

import java.util.List;

/**
 * Created by yeahmobi on 2015/3/20.
 */
@Service
public class GeolocationRdbServiceImpl extends DaoTemplate implements GeolocationRdbService {
    @Override
    public List<AdGeolocation> searchListByKey(String q) {
        String key = q.replaceAll("'", "\\\\'");
        String sql = "SELECT * FROM (SELECT c_id,c_key,c_name,c_code,c_type,supports_region,supports_city FROM country_code WHERE  c_name LIKE '" +
                key + "%' ORDER BY c_name) a UNION SELECT * FROM (SELECT c_id,c_key,c_name,c_code,c_type,supports_region,supports_city FROM country_code WHERE  c_key LIKE '" +
                key + "%' ORDER BY c_name) b";
        return getJdbcTemplate().query(sql, DefaultRowMapper.autoRowMapper(AdGeolocation.class));
    }

    @Override
    public List<AdGeolocation> searchListByKeys(String keys) {
        String sql = "SELECT c_id,c_key,c_name,c_code,c_type,supports_region,supports_city FROM country_code WHERE c_key in (" + keys + ") ";
        List list = (List) getJdbcTemplate().query(sql, DefaultRowMapper.autoRowMapper(AdGeolocation.class));
        if (list != null && list.size() > 0) {
            return list;
        } else {
            return null;
        }
    }

    @Override
    public List<AdGeolocation> getAll() {
        String sql = "select * from country_code";
        return getJdbcTemplate().query(sql, DefaultRowMapper.autoRowMapper(AdGeolocation.class));
    }

    @Override
    public void updateFbUsers(Long id, Long fbUsers) {
        String sql = "update country_code set fb_users_number = ? where c_id = ?";
        getJdbcTemplate().update(sql, new Object[]{fbUsers, id});
    }
}
